package com.ztomorrow.ying_cun_plus.manager;

import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.ztomorrow.ying_cun_plus.dao.mapper.BookContentMapper;
import com.ztomorrow.ying_cun_plus.dao.po.BookContent;
import com.ztomorrow.ying_cun_plus.utils.CacheUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import static com.ztomorrow.ying_cun_plus.constant.front.CacheConstant.*;

@Component
@RequiredArgsConstructor
public class BookContentCacheManager {

    private final CacheUtils cacheUtils;
    private final BookContentMapper bookContentMapper;

    /**
     * 根据章节ID获取，章节内容
     */
    public String getBookContent(Long chapterId) {
        String cache = cacheUtils.getCacheOne(
                v -> (String) v,
                CAFFEINE_BOOK_CONTENT + chapterId, REDIS_BOOK_CONTENT + chapterId,
                v -> v);
        if (cache != null) return cache;
        BookContent bookContent = new LambdaQueryChainWrapper<>(bookContentMapper)
                .eq(BookContent::getChapterId, chapterId)
                .last("limit 1")
                .one();
        cacheUtils.saveCacheOne(bookContent.getContent(),
                CAFFEINE_BOOK_CONTENT + chapterId,
                REDIS_BOOK_CONTENT + chapterId, REDIS_BOOK_CONTENT_TTL,
                Object::toString);
        return bookContent.getContent();
    }
}
